<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true" label-width="120px">
            <el-row>
                <el-col :span="6">
                    <el-form-item label="规则名称" prop="rulesName">
                        <el-input
                            v-model="queryParams.rulesName" placeholder="请输入规则名称" clearable size="default" style="width: 160px"
                            @keyup.enter="handleQuery" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item>
                        <search-button @click="handleQuery"/>
                        <reset-button @click="resetQuery"/>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <add-button @click="handleAdd"/>
            <delete-button @click="handleDelete" :disabled="selectedRows.length === 0"/>
            <right-toolbar v-model:showSearch="showSearch" @query-table="getList"/>
        </el-row>

        <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50" />
            <el-table-column label="规则分类" prop="rulesType" :show-overflow-tooltip="true" min-width="100" />
            <el-table-column label="规则名称" prop="rulesName" :show-overflow-tooltip="true" min-width="100" />
            <el-table-column label="规则说明" prop="remark" :show-overflow-tooltip="true" min-width="100"/>
            <el-table-column label="规则示例" prop="example" :show-overflow-tooltip="true" min-width="100"/>
            <el-table-column label="代码" prop="scriptContext" align="center" :show-overflow-tooltip="true" width="80">
                <template #default="scope">
                    <text-button text="代码" @click="handleCode(scope.row)"></text-button>
                </template>
            </el-table-column>
            <el-table-column label="更新时间" prop="updateTime" align="center" width="160" />
            <el-table-column label="操作" align="center" width="240" class-name="small-padding fixed-width">
                <template #default="scope">
                    <text-edit-button @click="handleUpdate(scope.row)"/>
                    <text-delete-button
                        @click="handleDelete(scope.row)"
                        :title="'是否确认删除记录?'" />
                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改角色配置对话框 -->
        <el-dialog v-el-drag-dialog :title="title" :close-on-click-modal="false" v-model="open" width="800px" append-to-body>
            <el-form label-width="120px">
                <el-form-item label="规则分类">
                    <el-select v-model="form.rulesType">
                        <el-option v-for="item in typeList" :key="item.dictLabel" :label="item.dictLabel" :value="item.dictLabel" />
                    </el-select>
                </el-form-item>
                <el-form-item label="规则名称">
                    <el-input v-model="form.rulesName"/>
                </el-form-item>
                <el-form-item label="规则示例">
                    <el-input v-model="form.example"/>
                </el-form-item>
                <el-form-item label="规则说明">
                    <el-input v-model="form.remark" type="textarea" :rows="4" />
                </el-form-item>
            </el-form>
        <dialog-footer @ok="submitForm" @cancel="cancel"/>
    </el-dialog>

        <!-- 代码编辑对话框 -->
        <el-dialog
            v-el-drag-dialog
            title="编辑规则代码"
            v-model="codeOpen"
            width="70%"
            top="8vh"
            :fullscreen="false"
            class="code-dialog"
            append-to-body>
            <div style="height: calc(80vh - 100px); min-height: 400px">
                <monaco-editor
                    v-model:value="codeContent"
                    @changeTextArea="changeTextArea"
                    ref="monacoEditorRef"
                    class="script-textarea"
                    language="java"
                    :options="{
                          minimap: { enabled: false },
                          automaticLayout: true, // 新增自动布局
                          scrollBeyondLastLine: false
                    }"
                    style="height: 100%"
                />
            </div>
            <template #footer>
                <el-button @click="codeOpen = false">取消</el-button>
                <el-button type="primary" @click="submitCode">保存</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>

import {ref, reactive, onMounted, nextTick,} from 'vue'
import { useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import TextButton from '@/components/Zmids/Buttons/TextButton.vue'
import {search, insert, deleteByIds, updateById, selectById, getDefaultScript} from '@data/api/data/datarules'
import { getDicts } from '@base/api/base/dict/data'
import monacoEditor from '../dataDevelopment/disposition/monaco-editor.vue'

const router = useRouter()

const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    rulesName: undefined,
})

const form = reactive({
    rulesType: '',
    rulesName: '',
    example: '',
    remark: ''
})

const showSearch = ref(true)
const loading = ref(false)
const total = ref(0)
const dataList = ref([])
const open = ref(false)
const title = ref('')
const selectedRows = ref([])
const ids = ref([])

const codeOpen = ref(false)
const codeContent = ref('')
const codeContentValue = ref(null)
const currentCodeId = ref(null)
const monacoEditorRef = ref(null);

// 表单验证规则
const rules = reactive({
    rulesType: [{ required: true, message: '规则分类不能为空', trigger: 'blur' }],
    rulesName: [{ required: true, message: '规则名称不能为空', trigger: 'blur' }]
})

const typeList = ref([]);
const getTypeList= () => {
    getDicts('data_rules_type').then((response) => {
        typeList.value = response.data
        console.log(typeList.value)
    })
};

// 生命周期钩子
onMounted(() => {
    getList()
    getTypeList()
})

// 方法定义
const getList = async () => {
    try {
        loading.value = true
        const res = await search(queryParams)
        dataList.value = res.data.list
    } finally {
        loading.value = false
    }
}

const handleQuery = () => {
    queryParams.pageNum = 1
    getList()
}

const resetQuery = () => {
    queryParams.rulesName = undefined
    queryParams.pageNum = 1
    queryParams.pageSize = 10
    getList()
}

const handleAdd = () => {
    title.value = '添加规则'
    resetForm()
    open.value = true
}

const handleSelectionChange = (val) => {
    selectedRows.value = val
    ids.value = val.map(item => item.id)
}

const handleDelete = (row) => {
    const deleteIds = row ? row.id : ids.value.join(",");
    console.log('deleteIds',deleteIds)
    deleteByIds(deleteIds).then(res=>{
        ElMessage.success('删除成功');
        getList();
    })
}

const handleUpdate = (row) => {
    title.value = '修改规则'
    // Object.assign(form, row)
    selectById(row.id).then((response) => {
        console.log('response',response)
        Object.assign(form, response.data)
    })
    open.value = true
}

const changeTextArea = (value) => {
    codeContentValue.value = value;
}

// 处理代码按钮点击
const handleCode = (row) => {
    currentCodeId.value = row.id
    codeContent.value = row.scriptContext
    codeOpen.value = true
    const initialContent = row.scriptContext || ''
    nextTick(() => {
        monacoEditorRef.value?.setData(initialContent)
    })
}
// 提交代码修改
const submitCode = async () => {
    try {
        console.log(codeContentValue.value)
        await updateById({
            id: currentCodeId.value,
            scriptContext: codeContentValue.value
        })
        ElMessage.success('代码保存成功')
        codeOpen.value = false
        getList()
    } catch (err) {
        console.error('保存失败:', err)
    }
}

const submitForm = () => {
    try {
        // 提交表单逻辑
        let fun = title.value === '添加规则' ? insert : updateById
        fun(form).then(res => {
            open.value = false
            getList()
        })
    } catch (err) {
        console.error('提交失败:', err)
    }
}

const cancel = () => {
    open.value = false
    resetForm()
}

const resetForm = () => {
    form.rulesType = ''
    form.rulesName = ''
    form.example = ''
    form.remark = ''
}

</script>

<style lang="scss" scoped>
::v-deep .code-dialog {
    .el-dialog__body {
        padding: 10px 20px;
    }
    .el-dialog__footer {
        padding: 10px 20px;
    }
}
</style>